package cate.game.pvp.eliterace.handler;

import cate.game.pvp.eliterace.data.EliteRaceSpec;
import cate.game.pvp.eliterace.data.EliteRaceVideo;
import cate.game.pvp.eliterace.data.EliteRaceVideoData;
import org.apache.commons.compress.utils.Lists;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;

public class BothEliteRaceVideoOperation implements EliteRaceVideoOperation {

    private final EliteRaceVideoData videData;
    private final Consumer<EliteRaceVideo> consumer;

    public BothEliteRaceVideoOperation(Supplier<EliteRaceVideoData> videDataSupplier,
                                       Consumer<EliteRaceVideo> consumer) {
        this.videData = Objects.requireNonNull(videDataSupplier.get());
        this.consumer = Objects.requireNonNull(consumer);
    }

    @Override
    public void upsert(EliteRaceSpec spec, EliteRaceVideo video) {
        this.videData.addValue(video);
        this.videData.addIndex(spec.toString(), video.getUid(), video);
    }

    @Override
    public void handle(EliteRaceSpec spec) {
        List<EliteRaceVideo> queryList = query(spec);
        if (CollectionUtils.isEmpty(queryList)) {
            return;
        }
        queryList.forEach(consumer::accept);
    }

    private List<EliteRaceVideo> query(EliteRaceSpec spec) {
        Map<String, EliteRaceVideo> indexMap = videData.getIndex(spec.toString());
        return CollectionUtils.isEmpty(indexMap)
                ? Lists.newArrayList()
                : Lists.newArrayList(indexMap.values().iterator());
    }
}
